package com.yzx.lifeassistants.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;

import com.haarman.listviewanimations.swinginadapters.prepared.SwingBottomInAnimationAdapter;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.yalantis.contextmenu.lib.ContextMenuDialogFragment;
import com.yalantis.contextmenu.lib.MenuObject;
import com.yalantis.contextmenu.lib.MenuParams;
import com.yalantis.contextmenu.lib.interfaces.OnMenuItemClickListener;
import com.yzx.lifeassistants.GlobalParams;
import com.yzx.lifeassistants.R;
import com.yzx.lifeassistants.adapter.RunningAdapter;
import com.yzx.lifeassistants.base.BaseActivity;
import com.yzx.lifeassistants.bean.RunningInfo;
import com.yzx.lifeassistants.common.CommonConstant;
import com.yzx.lifeassistants.utils.LogcatUtils;
import com.yzx.lifeassistants.utils.ToastUtils;
import com.yzx.lifeassistants.view.widget.CircularLoadingDialog;

/**
 * @Description: 约跑
 * @author: yzx
 * @time: 2016-3-7 下午1:27:01
 */
public class RunningActivity extends BaseActivity implements OnClickListener,
		OnItemClickListener, OnMenuItemClickListener {
	private RelativeLayout topRL;//
	private ImageButton backBtn;// 返回按钮
	private ImageButton moreBtn;// 更多按钮
	private RelativeLayout searchRL;// 搜索框
	private ListView runningLV;// 约跑列表
	private PullToRefreshListView runningPTRLV;// 刷新
	private ILoadingLayout runningILL;// 加载

	private CircularLoadingDialog dialog;// 加载
	private static final int STATE_REFRESH = 0;// 下拉刷新
	private static final int STATE_MORE = 1;// 加载更多
	private int limit = 10; // 每页的数据是10条
	private int curPage = 0; // 当前页的编号，从0开始
	private List<Boolean> isList;//
	private List<RunningInfo> dataList;// 约跑列表
	private RunningAdapter adapter;// 列表适配器

	private FragmentManager fragmentManager;//
	private ContextMenuDialogFragment mMenuDialogFragment;//
	private int topHeight;// 顶部高度

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_running);
		initView();
		setListener();
		initMenuFragment();
		initData();
	}

	/**
	 * 
	 * @Description: 初始化控件
	 */
	private void initView() {
		topRL = (RelativeLayout) findViewById(R.id.running_top_rl);
		backBtn = (ImageButton) findViewById(R.id.running_back_btn);
		moreBtn = (ImageButton) findViewById(R.id.running_more_btn);
		searchRL = (RelativeLayout) findViewById(R.id.running_search_rl);
		runningPTRLV = (PullToRefreshListView) findViewById(R.id.running_listview);
		runningILL = runningPTRLV.getLoadingLayoutProxy();
		runningILL.setLastUpdatedLabel("");
		runningILL.setPullLabel("继续拖动");
		runningILL.setRefreshingLabel("正在装载数据···");
		runningILL.setReleaseLabel("放开装载更多");
		runningLV = runningPTRLV.getRefreshableView();

	}

	/**
	 * 
	 * @Description: 设置监听
	 */
	private void setListener() {
		backBtn.setOnClickListener(this);
		moreBtn.setOnClickListener(this);
		searchRL.setOnClickListener(this);
		// 滑动监听
		runningPTRLV.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if (firstVisibleItem == 0) {
					runningILL.setLastUpdatedLabel("");
					runningILL.setPullLabel("下拉刷新");
					runningILL.setRefreshingLabel("加载中···");
					runningILL.setReleaseLabel("释放刷新");
				} else if (firstVisibleItem + visibleItemCount == totalItemCount) {
					runningILL.setLastUpdatedLabel("");
					runningILL.setPullLabel("继续拖动");
					runningILL.setRefreshingLabel("正在装载数据···");
					runningILL.setReleaseLabel("放开装载更多");
				}
			}
		});
		// 下拉刷新监听
		runningPTRLV.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				// 下拉刷新(从第一页开始装载数据)
				queryRunning(0, STATE_REFRESH);
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				// 上拉加载更多(加载下一页数据)
				queryRunning(curPage, STATE_MORE);
			}

		});
		runningLV.setOnItemClickListener(this);
	}

	/**
	 * 
	 * @Description: 初始化菜单
	 */
	private void initMenuFragment() {
		fragmentManager = getSupportFragmentManager();
		MenuParams menuParams = new MenuParams();
		int w = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		int h = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		topRL.measure(w, h);
		topHeight = topRL.getMeasuredHeight();
		menuParams.setActionBarSize(topHeight);
		menuParams.setMenuObjects(getMenuObjects());
		menuParams.setClipToPadding(false);
		menuParams.setClosableOutside(true);
		mMenuDialogFragment = ContextMenuDialogFragment.newInstance(menuParams);
		mMenuDialogFragment.setItemClickListener(this);
	}

	/**
	 * 
	 * @Description: 设置列表项
	 */
	private List<MenuObject> getMenuObjects() {
		List<MenuObject> menuObjects = new ArrayList<MenuObject>();
		int mColor = getResources().getColor(R.color.actionbar_color);
		// 关闭
		MenuObject close = new MenuObject();
		close.setResource(R.drawable.icon_menu_close);
		close.setBgColor(mColor);
		// 发布
		MenuObject addMenu = new MenuObject("发布约跑");
		addMenu.setResource(R.drawable.icon_menu_add);
		addMenu.setBgColor(mColor);
		addMenu.setMenuTextAppearanceStyle(R.style.TextViewStyle);
		// 我的
		MenuObject myMenu = new MenuObject("我的约跑");
		myMenu.setResource(R.drawable.icon_menu_running);
		myMenu.setBgColor(mColor);
		myMenu.setMenuTextAppearanceStyle(R.style.TextViewStyle);
		// 我的收藏
		MenuObject myLove = new MenuObject("我的收藏");
		myLove.setResource(R.drawable.icon_menu_runnning_love);
		myLove.setBgColor(mColor);
		myLove.setMenuTextAppearanceStyle(R.style.TextViewStyle);

		menuObjects.add(close);
		menuObjects.add(addMenu);
		menuObjects.add(myMenu);
		menuObjects.add(myLove);
		return menuObjects;
	}

	/**
	 * 
	 * @Description: 初始化数据
	 */
	private void initData() {
		dialog = new CircularLoadingDialog(this);
		isList = new ArrayList<Boolean>();
		dataList = new ArrayList<RunningInfo>();
		adapter = new RunningAdapter(runningLV, this, dataList, isList);
		SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(
				adapter);
		swingBottomInAnimationAdapter.setAbsListView(runningLV);
		runningLV.setAdapter(swingBottomInAnimationAdapter);
		// queryRunning(0, STATE_REFRESH);
	}

	/**
	 * 
	 * @Description: 搜索约跑
	 */
	private void queryRunning(int page, final int actionType) {
		dialog.show();
		BmobQuery<RunningInfo> query = new BmobQuery<RunningInfo>();
		query.order("-updatedAt");// 按照修改时间升序
		query.setLimit(limit);
		query.setSkip(page * limit);
		query.findObjects(this, new FindListener<RunningInfo>() {
			@Override
			public void onSuccess(List<RunningInfo> list) {// 查询成功
				LogcatUtils.i("查询约跑列表信息成功");
				dialog.dismiss();
				// 若list.size()>0只剩一项时删不掉
				if (list.size() > -1) {
					if (actionType == STATE_REFRESH) {
						// 当是下拉刷新操作时，将当前页的编号重置为0，清空，重新添加
						curPage = 0;
						dataList.clear();
						isList.clear();
					}
					for (RunningInfo info : list) {
						dataList.add(info);
						if (GlobalParams.userInfo.getUsername().equals(
								info.getUsername())) {
							isList.add(true);
						} else {
							isList.add(false);
						}
					}
					// 这里在每次加载完数据后，将当前页码+1
					// 这样在上拉刷新的onPullUpToRefresh方法中就不需要操作curPage了
					curPage++;
				}
				if (actionType == STATE_MORE && list.size() < 1) {
					showToast("暂时还未有更多的约跑信息~", true);
				}
				if (actionType == STATE_REFRESH && list.size() < 1) {
					showToast("暂时还未有约跑信息~", true);
				}
				runningPTRLV.onRefreshComplete();
				adapter.notifyDataSetChanged();
			}

			@Override
			public void onError(int code, String message) {// 查询失败
				LogcatUtils.e("查询约跑列表信息失败：" + code + " " + message);
				dialog.dismiss();
				switch (code) {
				case 101: {
					showToast("暂时还未有约跑信息~", true);
					break;
				}
				case 9010: {// 网络超时
					showToast("网络超时，请检查您的手机网络~", false);
					break;
				}
				case 9016: {// 无网络连接，请检查您的手机网络
					showToast("无网络连接，请检查您的手机网络~", false);
					break;
				}
				default: {
					showToast("查询失败，请刷新重试~", false);
					break;
				}
				}
				runningPTRLV.onRefreshComplete();
				adapter.notifyDataSetChanged();

			}
		});
	}

	/**
	 * 
	 * @Description: 按键监听
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.running_back_btn: {// 返回
			finish();
			break;
		}
		case R.id.running_more_btn: {// 更多
			if (fragmentManager
					.findFragmentByTag(ContextMenuDialogFragment.TAG) == null) {
				mMenuDialogFragment.show(fragmentManager,
						ContextMenuDialogFragment.TAG);
			}
			break;
		}
		case R.id.running_search_rl: {// 搜索
			Intent intent = new Intent(this, RunningSearchActivity.class);
			startActivity(intent);
			break;
		}
		default:
			break;
		}
	}

	/**
	 * 
	 * @Description: 列表按键监听
	 */
	@Override
	public void onItemClick(AdapterView<?> adapterView, View view,
			int position, long arg3) {
		Intent intent = new Intent(this, RunningInfoActivity.class);
		intent.putExtra("RUNNING_INFO", dataList.get(position - 1));
		startActivity(intent);
	}

	/**
	 * 
	 * @Description: 右菜单列表按键监听
	 */
	@Override
	public void onMenuItemClick(View clickedView, int position) {
		switch (position) {
		case 1: {// 发布约跑
			Intent intent = new Intent(this, AddRunningActivity.class);
			intent.putExtra("from", CommonConstant.FROM_RUNNING);
			startActivityForResult(intent,
					CommonConstant.REQUESTCODE_ADD_RUNNING);
			break;
		}
		case 2: {// 我的约跑
			Intent intent = new Intent(this, MyRunningActivity.class);
			startActivity(intent);
			break;
		}
		case 3: {// 我的收藏
			Intent intent = new Intent(this, RunningLoveActivity.class);
			startActivity(intent);
			break;
		}
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (CommonConstant.RESULTCODE_ADD_RUNNING_OK == resultCode) {
			showToast("发布约跑信息成功~", true);
			queryRunning(0, STATE_REFRESH);
		}
	}

	/**
	 * 
	 * @Description: Toast显示信息
	 */
	private void showToast(String message, Boolean isInfo) {
		if (isInfo) {
			ToastUtils.showInfoToast(this, message, R.id.running_top_ll);
		} else {
			ToastUtils.showAlertToast(this, message, R.id.running_top_ll);
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		queryRunning(0, STATE_REFRESH);
	}
}
